var jabber = {};

jabber.JabberApp = function(){};
core.extendClass('jabber.JabberApp', 'core.JSApplication');

jabber.AddEntry = function(){};
core.extendClass('jabber.AddEntry', 'core.JSDialog');

jabber.AddEntry.prototype.createDialog = function(aData){
    var instance = this;
    var dlg = new core.Dialog({
        title: 'Add new entry:',
        maxWidth: 300,
        items:[
            new core.Label({
                text:'User JID:',
                align: 'left'
            }),
            new core.form.TextField({
                id: 'user'
            }),
            new core.Label({
                text:'User nickname (optional):',
                align: 'left'
            }),
            new core.form.TextField({
                id: 'name'
            }),
            new core.Box({
                columns: '1, d',
                items:[
                    new core.form.Button({
                        text: 'Add',
                        handler: function(){
                            instance.sendMessage('addEntry', dlg.body.getValue(), null, null, dlg);
                        },
                        align: 'right'
                    }),
                    new core.form.Button({
                        text: 'Cancel',
                        handler: function(){
                            instance.sendMessage('closeDialog', null, null, null, dlg);
                        }
                    })
                ]
            })
        ],
        rows: 'd, d, d, d, d',
        columns: '1'
    });
    return dlg;
};

jabber.GroupMessage = function(){};
core.extendClass('jabber.GroupMessage', 'core.JSDialog');

jabber.GroupMessage.prototype.createDialog = function(aData){
    var instance = this;
    this.count = new core.Label({
        text: 'Characters: 0',
        align: 'left'
    });
    this.textarea = new core.form.TextArea({
        colspan: 3,
        id: 'message',
        minHeight: 50
    });
    this.textarea.on('change', function(t){
        instance.count.setText('Characters: '+t.getValue().length);
    });
    this.textarea.on('keydown', function(t, e){
        if(e.which==13 || e.which==10){
            var textToSend = $.trim(t.getValue());
            if(textToSend.length>0){
                instance.sendMessage('sendMessage', {
                    message: textToSend
                }, null, null, instance.textarea);
            }
            return false;
        }
        return true;
    });
    var dlg = new core.Dialog({
        title: 'Group message:',
        maxWidth: 400,
        defaultItem: this.textarea,
        items:[
            new core.Label({
                colspan: 3,
                text: aData.recipients,
                align: 'left'
            }),
            this.textarea,
            this.count,

            new core.form.Button({
                text: 'Send',
                handler: function(){
                    var textToSend = $.trim(instance.textarea.getValue());
                    if(textToSend.length>0){
                        instance.sendMessage('sendMessage', {
                            message: textToSend
                        }, null, null, instance.textarea);
                    }
                }
            }),
            new core.form.Button({
                text: 'Cancel',
                handler: function(){
                    instance.sendMessage('closeDialog', dlg.body.getValue(), null, null, dlg);
                }
            })
        ],
        columns: '1, d, d',
        rows: 'd, d, d, d'
    });

    return dlg;
};

jabber.SettingsDialog = function(){};
core.extendClass('jabber.SettingsDialog', 'core.JSDialog');

jabber.SettingsDialog.prototype.createDialog = function(aData){
    var instance = this;
    this.nickname = new core.form.TextField({
        id: 'name'
    });
    this.userName = new core.form.TextField({
        id: 'username'
    });
    this.autoAway = new core.form.CheckBox({
        id: 'autoaway',
        text: 'Auto set away after disconnect',
        colspan: 2
    });
    this.hideOffline = new core.form.CheckBox({
        id: 'hideoffline',
        text: 'Hide offline users',
        colspan: 2
    });
    this.showNotify = new core.form.CheckBox({
        id: 'shownotify',
        text: 'Show new message notifications',
        colspan: 2
    });
    this.history = new core.form.CheckBox({
        id: 'history',
        text: 'Save history',
        colspan: 2
    });
    this.historyItems = new core.form.TextField({
        id: 'history_items',
        minWidth: 20
    });
    this.resource = new core.form.TextField({
        id: 'resource'
    });
    this.password = new core.form.TextField({
        id: 'password',
        password: true
    });
    this.useHostPort = new core.form.CheckBox({
        id: 'hostport',
        text: 'Use custom host and port',
        colspan: 2
    });
    this.host = new core.form.TextField({
        id: 'host'
    });
    this.port = new core.form.TextField({
        id: 'port'
    });

    var dlg = new core.Dialog({
        title: 'Jabber settings:',
        maxWidth: 400,
        items:[
            core.createLabel('Nickname:'), this.nickname,
            core.createLabel('Username (JID):'), this.userName,
            core.createLabel('Password:'), this.password,
            this.autoAway,
            this.hideOffline,
            this.showNotify,
            this.history,
            new core.Box({
                colspan: 2,
                items: [
                    new core.Label({
                        text: 'Show last',
                        align: 'left',
                        minWidth: 50
                    }), this.historyItems,
                    new core.Label({
                        text: 'messages in new chat',
                        align: 'left'
                    })
                ], columns: '0.1, d, 0.9',
                rows: 'd'
            }),
            core.createLabel('Resource:'), this.resource,
            this.useHostPort,
            core.createLabel('Hostname:'), this.host,
            core.createLabel('Port number:'), this.port,
            new core.Label({
                align: 'left',
                colspan: 2,
                text: '* Hint: for google accounts (GMail and Google Apps) use '+
                    'host <b>talk.google.com</b> and port <b>5222</b>'
            }),
            new core.Box({
                colspan: 2,
                columns: '1, 1',
                items: [
                    new core.form.Button({
                        text: 'Save',
                        align: 'right',
                        handler: function(){
                            instance.sendMessage('okClick', dlg.body.getValue(), null, null, dlg);
                        }
                    }), new core.form.Button({
                        text: 'Cancel',
                        align: 'left',
                        handler: function(){
                            instance.sendMessage('cancelClick', null, null, null, dlg);
                        }
                    })
                ]
            })
        ],
        columns: '0.3, 0.7',
        rows: 'd, d, d, d, d, d, d, d, d, d, d, d, d, d'
    });
    dlg.body.setValue(aData);
//    this.userName.focus();
    return dlg;
};

jabber.Roster = function(){};
core.extendClass('jabber.Roster', 'core.JSFrame');

jabber.Roster.prototype.loadContents = function(){
    var instance = this;
    var toolbar = new core.Tabs({
        toolbar: true,
        cls: 'toolbar'
    });

    this.statusBtn = new core.form.Button({
        icon: 'jabber_t_icn jabber_t_status',
        tooltip: 'Change status',
        menu: [
            {
                cls: 'jabber_icn jabber_1',
                text: 'Online',
                handler: function(){
                    instance.sendMessage('setStatus', {
                        status: 1
                    }, null, null, instance.statusBtn);
                    return true;
                }
            },{
                cls: 'jabber_icn jabber_2',
                text: 'Away',
                handler: function(){
                    instance.sendMessage('setStatus', {
                        status: 2
                    }, null, null, instance.statusBtn);
                    return true;
                }
            },{
                cls: 'jabber_icn jabber_3',
                text: 'Extended away',
                handler: function(){
                    instance.sendMessage('setStatus', {
                        status: 3
                    }, null, null, instance.statusBtn);
                    return true;
                }
            },{
                cls: 'jabber_icn jabber_4',
                text: 'Don\'t disturb' ,
                handler: function(){
                    instance.sendMessage('setStatus', {
                        status: 4
                    }, null, null, instance.statusBtn);
                    return true;
                }
            },{
                cls: 'jabber_icn jabber_0',
                text: 'Offline',
                handler: function(){
                    instance.sendMessage('setStatus', {
                        status: 0
                    }, null, null, instance.statusBtn);
                    return true;
                }
            }
        ]
    });
    this.settingsBtn = new core.form.Button({
        icon: 'jabber_t_icn jabber_t_settings',
        tooltip: 'Change settings',
        handler: function(){
            instance.send({
                method: 'openSettingsDialog',
                disable: instance.frame
            });
        }
    });
    this.messageBtn = new core.form.Button({
        icon: 'jabber_t_icn jabber_t_chat',
        tooltip: 'Start new chat with selected contact',
        handler: function(){
            instance.send({
                method: 'openSelectedChat',
                disable: instance.frame
            });
        }
    });
    this.addBtn = new core.form.Button({
        icon: 'jabber_t_icn jabber_t_add',
        tooltip: 'Add new contact to selected group',
        handler: function(){
            instance.sendMessage('startAddEntry');
        }
    });
    this.removeBtn = new core.form.Button({
        icon: 'jabber_t_icn jabber_t_remove',
        tooltip: 'Remove selected contact',
        handler: function(){
            instance.sendMessage('removeEntry');
        }
    });
    toolbar.addTab(this.statusBtn, this.settingsBtn, this.messageBtn, this.addBtn, this.removeBtn);
    this.frame.addToolbar(toolbar);

    this.tree = new core.tree.TreePanel({
        
    });
    this.setContent([this.tree], '1', '1');
//#ifdef DESKTOP
    this.tree.on('add_item', function(tree, event, item){
//        core.log('added item('+item.text+'): '+item.data.draggable);
        if(item.data.draggable){
            item.enableDragging(tree, item, item.contentDiv);
        }
    }).on('accept_target', function(tree, e, item, target){
//        core.log('accept_target', target.text, target.data.group);
        if(target.data && target.data.group)
            return true;
        return false;
    }).on('dd_end', function(tree, e, item, target){
        core.log('Moving', item.text, 'to', target.text);
        instance.send({
            method: 'moveEntry',
            message: {
                user: item.id,
                group: target.id
            },
            disable: instance.tree
        });
    });
//#endif
    this.tree.on('state_change', function(tree, event, item){
//        core.log('Sending state of item of '+item.id, 'to', item.collapsed);
        instance.sendMessage('setState', {
            id: item.id,
            collapsed: item.collapsed
        });
    });
    this.tree.on('select', function(tree, event, item){
        var id = '';
        if(item)
            id = item.id;
        instance.sendMessage('selectionChanged', {
            id: id
        });
        return false;
    });
    
    this.tree.on('item_dbl_click', function(tree, event, item){
        instance.send({
            method: 'openChat',
            message: {
                id: item.id
            },
            disable: tree
        });
        return false;
    });
    this.reloadTree();
}

jabber.Roster.prototype.treeItemModified = function(aData){
    this.tree.treeItemModified(aData);
}

jabber.Roster.prototype.treeItemRemoved = function(aData){
    this.tree.treeItemRemoved(aData);
}

jabber.Roster.prototype.treeItemInserted = function(aData){
    this.tree.treeItemInserted(aData);
}

jabber.Roster.prototype.changeTreeItemState = function(aData){
    this.tree.changeTreeItemState(aData);
}

jabber.Roster.prototype.newTree = function(aData){
    this.tree.loadTree(aData);
}

jabber.Roster.prototype.reloadTree = function(){
    var instance = this;
    this.sendMessage('getTree', {}, function(data){
        instance.tree.loadTree(data);
    }, null, this.tree);
};

jabber.Chat = function(){};
core.extendClass('jabber.Chat', 'core.JSFrame');

jabber.Chat.prototype.newMessage = function(aData, aSkipUpdate){
    var message = core.newDiv(null, 'jabber_message');
    if(aData.archive)
        $(message).addClass('jabber_message_archive');
    var classSuffix = aData.system?'system':aData.incoming?'incoming':'outgoing';
    var dateSpan = core.newElement(message, 'span', 'date_'+classSuffix);
//#ifdef DESKTOP
    $(dateSpan).html('['+aData.date+']');
//#endif

//#ifdef MOBILE
    $(dateSpan).html('['+aData.mdate+']');
//#endif

    $(message).append(dateSpan);
    if(!aData.system){
        var fromSpan = core.newElement(message, 'span', 'from_'+classSuffix);
        $(fromSpan).text(' <'+aData.from+'>');
        $(message).append(fromSpan);
    }
    $(message).append(': '+aData.message);
    this.history.addContent(message);
    if(!aSkipUpdate)
        this.history.bodyChanged();
}

jabber.Chat.prototype.loadContents = function(){
    var instance = this;
    this.frame.body.on('focus', function(){
        instance.sendMessage('chatFocused');
    });
    this.frame.body.on('unfocus', function(){
        instance.sendMessage('chatUnFocused');
    });
    this.history = new core.HTMLPanel({
        bottom: true,
        colspan: 1
    });
    this.message = new core.form.TextArea({
        id: 'message'
    });
    this.message.on('change', function(t){
        instance.frame.updateStatus('Characters: '+t.getValue().length);
    });
    var sendHandler = function(t){
        var textToSend = $.trim(t.getValue());
        if(textToSend.length>0){
            instance.sendMessage('sendMessage', {
                message: textToSend
            }, function(){
                instance.message.setValue('');
//                instance.message.doFocus();
            }, null, instance.message);
        }
    }
    this.message.on('keydown', function(t, e){
        if(e.which==13 || e.which==10){
            if(e.ctrlKey){
//                e.ctrlKey = false;
//                core.log('Ctrl key detected: '+$(instance.message.control).getSelection().start);
                $(instance.message.control).replaceSelection('\n');
                return false;
            }
            sendHandler(t);
            return false;
        }
        return true;
    });
//    this.btn = new core.form.Button({
//        text: 'Send',
//        handler: function(){
//            sendHandler(instance.message);
//        }
//    })
    this.message.minHeight = 50;
    this.setContent([this.history, this.message], '1', '1, d', this.message);
    this.frame.updateStatus('Characters: 0');
    this.sendMessage('getHistory', {}, function(aData){
        var arr = $.makeArray(aData.history);
        instance.history.setHTML('');
        for (var i = 0; i < arr.length; i++) {
            instance.newMessage(arr[i], true);
        }
        instance.history.bodyChanged();
    });
};
